package gov.pbc.nn.kjgl.fxq.infoResearch.view;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.apache.commons.lang3.StringUtils;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.criterion.DetachedCriteria;
import org.hibernate.criterion.Order;
import org.hibernate.criterion.Restrictions;
import org.hibernate.transform.Transformers;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import com.bstek.bdf2.core.business.IUser;
import com.bstek.bdf2.core.context.ContextHolder;
import com.bstek.bdf2.core.exception.NoneLoginException;
import com.bstek.bdf2.core.orm.hibernate.ISessionCallback;
import com.bstek.dorado.annotation.DataProvider;
import com.bstek.dorado.annotation.DataResolver;
import com.bstek.dorado.annotation.Expose;
import com.bstek.dorado.data.entity.EntityState;
import com.bstek.dorado.data.entity.EntityUtils;
import com.bstek.dorado.data.provider.Criteria;
import com.bstek.dorado.data.provider.Page;
import com.bstek.dorado.data.variant.Record;

import gov.pbc.nn.core.bdf.entity.Dept;
import gov.pbc.nn.core.dao.CommonHibernateDao;
import gov.pbc.nn.core.dao.PbcnnCoreJdbcDao;
import gov.pbc.nn.kjgl.fxq.attachment.AttachmentEntity;
import gov.pbc.nn.kjgl.fxq.infoResearch.entity.HistoryDocEntity;
import gov.pbc.nn.kjgl.fxq.infoResearch.entity.InfoResearchEntity;
import gov.pbc.nn.kjgl.fxq.organInfor.entity.OrganInfor;
import gov.pbc.nn.kjgl.fxq.workDocument.view.WorkDocumentPR;

@Component(InfoResearchPR.BEAN_ID)
public class InfoResearchPR extends CommonHibernateDao {
	public static final String BEAN_ID = "infoResearchPR";

	@Resource(name = PbcnnCoreJdbcDao.BEAN_ID)
	private PbcnnCoreJdbcDao jdbcDao;

	@Resource(name = WorkDocumentPR.BEAN_ID)
	private WorkDocumentPR workDocumentPR;

	@Resource(name = HistoryDocPR.BEAN_ID)
	private HistoryDocPR historyDocPR;
	
	@DataProvider
	public List<OrganInfor> getAllOrgan(Map<String, String> parameter) throws Exception {
		IUser user = ContextHolder.getLoginUser();
		if (user == null)
			throw new NoneLoginException("请先登录！");
		if (user.getDepts() == null || user.getDepts().isEmpty())
			throw new NoneLoginException("您未设置部门！");
		Dept dept = (Dept) user.getDepts().get(0);
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("deptId", dept.getCDept().getId());
		if (parameter == null || StringUtils.isEmpty(parameter.get("filterValue"))) {
			return this.query("select o from OrganInfor o where o.deptId=:deptId and invalid=false", map);
		} else {
			String filterValue = parameter.get("filterValue").replace(' ', '%');
			map.put("filterValue", "%" + filterValue + "%");
			return this.query("select o from OrganInfor o where o.deptId=:deptId and invalid=false and o.organName like :filterValue", map);
		}
	}

	@DataProvider
	public void loadAllInfoResearchs(Page<InfoResearchEntity> page, Criteria criteria) throws Exception {
		IUser user = ContextHolder.getLoginUser();
		if (user == null)
			throw new NoneLoginException("请先登录！");
		if (user.getDepts() == null || user.getDepts().isEmpty())
			throw new NoneLoginException("您未设置部门！");
		Dept dept = (Dept) user.getDepts().get(0);
		List<String> childrenIds = this.workDocumentPR.getAllChildOrgDeptId(dept.getCDept().getParentId());
		// System.out.println(dept.getCDept().getName());
		childrenIds.add(dept.getCDept().getId());
		DetachedCriteria detachedCriteria = this.buildDetachedCriteria(criteria, InfoResearchEntity.class);
		detachedCriteria.add(Restrictions.or(Restrictions.eq("createUser", user.getUsername()), Restrictions.and(Restrictions.in("deptId", childrenIds), Restrictions.eq("state", 20))));
		detachedCriteria.add(Restrictions.eq("invalid", false));
		if (criteria != null && criteria.getOrders() != null && !criteria.getOrders().isEmpty()) {
			com.bstek.dorado.data.provider.Order order = criteria.getOrders().get(0);
			if (order.isDesc()) {
				detachedCriteria.addOrder(Order.desc(order.getProperty()));
			} else {
				detachedCriteria.addOrder(Order.asc(order.getProperty()));
			}
		} else {
			detachedCriteria.addOrder(Order.desc("createDate"));
		}
		this.pagingQuery(page, detachedCriteria);		
	}

	@DataResolver
	@Transactional
	public void saveInfoResearch(List<InfoResearchEntity> infoResearchEntities) throws Exception {
		IUser user = ContextHolder.getLoginUser();
		if (user == null)
			throw new NoneLoginException("请先登录！");
		if (user.getDepts() == null || user.getDepts().isEmpty())
			throw new NoneLoginException("您未设置部门！");
		Dept dept = (Dept) user.getDepts().get(0);
		for (InfoResearchEntity infoResearch : infoResearchEntities) {
			EntityState state = EntityUtils.getState(infoResearch);
			InfoResearchEntity infoResearchEntity = EntityUtils.toEntity(infoResearch);
			infoResearch.setState(10);
			if (state.equals(EntityState.NEW)) {
				infoResearch.setDeptId(dept.getCDept().getId());
				infoResearch.setDeptName(dept.getCDept().getName());
				this.save(infoResearch);
			} else if (state.equals(EntityState.MODIFIED)) {
				this.update(infoResearch);
			} else if (state.equals(EntityState.DELETED)) {
				this.delete(infoResearch);
			}

			List<HistoryDocEntity> historyDocEntitys = EntityUtils.getValue(infoResearchEntity, "docs");
			if (historyDocEntitys != null) {
				this.update(infoResearch);
				//for (HistoryDocEntity historyDocEntity : historyDocEntitys) {
				this.historyDocPR.saveHistoryDoc(historyDocEntitys);
				//}
			}			
		}
	}

	@Expose
	@DataResolver
	@Transactional
	public void submitInfoResearch(InfoResearchEntity infoResearch) throws Exception {
		if (infoResearch.getState() != 20) {
			infoResearch.setState(20);
			infoResearch.setSubmitDate(new Date());
			this.update(infoResearch);
		}
	}
}
